{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Flexbox layout\n",
    "\n",
    "The `HBox` and `VBox` classes above are special cases of the `Box` widget.\n",
    "\n",
    "The `Box` widget enables the entire CSS flexbox spec as well as the Grid layout spec, enabling rich reactive layouts in the Jupyter notebook. It aims at providing an efficient way to lay out, align and distribute space among items in a container.\n",
    "\n",
    "Again, the whole flexbox spec is exposed via the `layout` attribute of the container widget (`Box`) and the contained items. One may share the same `layout` attribute among all the contained items.\n",
    "\n",
    "### Acknowledgement\n",
    "\n",
    "The following flexbox tutorial on the flexbox layout follows the lines of the article [A Complete Guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) by Chris Coyier, and uses text and various images from the article [with permission](https://css-tricks.com/license/).\n",
    "\n",
    "### Basics and terminology\n",
    "\n",
    "Since flexbox is a whole module and not a single property, it involves a lot of things including its whole set of properties. Some of them are meant to be set on the container (parent element, known as \"flex container\") whereas the others are meant to be set on the children (known as \"flex items\").\n",
    "If regular layout is based on both block and inline flow directions, the flex layout is based on \"flex-flow directions\". Please have a look at this figure from the specification, explaining the main idea behind the flex layout.\n",
    "\n",
    "![Flexbox](images/flexbox.png)\n",
    "\n",
    "Basically, items will be laid out following either the `main axis` (from `main-start` to `main-end`) or the `cross axis` (from `cross-start` to `cross-end`).\n",
    "\n",
    "- `main axis` - The main axis of a flex container is the primary axis along which flex items are laid out. Beware, it is not necessarily horizontal; it depends on the flex-direction property (see below).\n",
    "- `main-start | main-end` - The flex items are placed within the container starting from main-start and going to main-end.\n",
    "- `main size` - A flex item's width or height, whichever is in the main dimension, is the item's main size. The flex item's main size property is either the ‘width’ or ‘height’ property, whichever is in the main dimension.\n",
    "cross axis - The axis perpendicular to the main axis is called the cross axis. Its direction depends on the main axis direction.\n",
    "- `cross-start | cross-end` - Flex lines are filled with items and placed into the container starting on the cross-start side of the flex container and going toward the cross-end side.\n",
    "- `cross size` - The width or height of a flex item, whichever is in the cross dimension, is the item's cross size. The cross size property is whichever of ‘width’ or ‘height’ that is in the cross dimension.\n",
    "\n",
    "### Properties of the parent\n",
    "\n",
    "![Container](images/flex-container.svg)\n",
    "\n",
    "\n",
    "#### display\n",
    "\n",
    "`display` can be `flex` or `inline-flex`. This defines a flex container (block or inline).\n",
    "\n",
    "#### flex-flow\n",
    "\n",
    "`flex-flow` is a shorthand for the `flex-direction` and `flex-wrap` properties, which together define the flex container's main and cross axes. Default is `row nowrap`.\n",
    "\n",
    "- `flex-direction` (column-reverse | column | row | row-reverse )\n",
    "\n",
    "  This establishes the main-axis, thus defining the direction flex items are placed in the flex container. Flexbox is (aside from optional wrapping) a single-direction layout concept. Think of flex items as primarily laying out either in horizontal rows or vertical columns.\n",
    "![Direction](images/flex-direction1.svg)\n",
    "\n",
    "- `flex-wrap` (nowrap | wrap | wrap-reverse)\n",
    "\n",
    "  By default, flex items will all try to fit onto one line. You can change that and allow the items to wrap as needed with this property. Direction also plays a role here, determining the direction new lines are stacked in.\n",
    "![Wrap](images/flex-wrap.svg)\n",
    "\n",
    "#### justify-content\n",
    "\n",
    "`justify-content` can be one of `flex-start`, `flex-end`, `center`, `space-between`, `space-around`. This defines the alignment along the main axis. It helps distribute extra free space left over when either all the flex items on a line are inflexible, or are flexible but have reached their maximum size. It also exerts some control over the alignment of items when they overflow the line.\n",
    "  ![Justify](images/justify-content.svg)\n",
    "\n",
    "#### align-items\n",
    "\n",
    "`align-items` can be one of `flex-start`, `flex-end`, `center`, `baseline`, `stretch`. This defines the default behaviour for how flex items are laid out along the cross axis on the current line. Think of it as the justify-content version for the cross-axis (perpendicular to the main-axis).\n",
    "   ![Items](images/align-items.svg)\n",
    "   \n",
    "#### align-content\n",
    "`align-content` can be one of `flex-start`, `flex-end`, `center`, `baseline`, `stretch`. This aligns a flex container's lines within when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis.\n",
    "![Items](images/align-content.svg)\n",
    "\n",
    "**Note**: this property has no effect when there is only one line of flex items.\n",
    "\n",
    "### Properties of the items\n",
    "\n",
    "![Item](images/flex-items.svg)\n",
    "\n",
    "The flexbox-related CSS properties of the items have no impact if the parent element is not a flexbox container (i.e. has a `display` attribute equal to `flex` or `inline-flex`).\n",
    "\n",
    "#### order\n",
    "By default, flex items are laid out in the source order. However, the `order` property controls the order in which they appear in the flex container.\n",
    "<img src=\"./images/order-2.svg\" alt=\"Order\" style=\"width: 500px;\"/>\n",
    "   \n",
    "#### flex\n",
    "`flex` is shorthand for three properties, `flex-grow`, `flex-shrink` and `flex-basis` combined. The second and third parameters (`flex-shrink` and `flex-basis`) are optional. Default is `0 1 auto`.\n",
    "   \n",
    "  - `flex-grow`\n",
    "\n",
    "    This defines the ability for a flex item to grow if necessary. It accepts a unitless value that serves as a proportion. It dictates what amount of the available space inside the flex container the item should take up.\n",
    "\n",
    "    If all items have flex-grow set to 1, the remaining space in the container will be distributed equally to all children. If one of the children a value of 2, the remaining space would take up twice as much space as the others (or it will try to, at least).\n",
    "      ![Grow](images/flex-grow.svg)\n",
    "\n",
    "  - `flex-shrink`\n",
    "\n",
    "    This defines the ability for a flex item to shrink if necessary.\n",
    "\n",
    "  - `flex-basis`\n",
    "\n",
    "    This defines the default size of an element before the remaining space is distributed. It can be a length (e.g. `20%`, `5rem`, etc.) or a keyword. The `auto` keyword means *\"look at my width or height property\"*.\n",
    " \n",
    "#### align-self\n",
    "\n",
    "`align-self` allows the default alignment (or the one specified by align-items) to be overridden for individual flex items.\n",
    "\n",
    "![Align](images/align-self.svg)\n",
    "\n",
    "### The VBox and HBox helpers\n",
    "\n",
    "The `VBox` and `HBox` helper classes provide simple defaults to arrange child widgets in vertical and horizontal boxes. They are roughly equivalent to:\n",
    "\n",
    "```Python\n",
    "def VBox(*pargs, **kwargs):\n",
    "    \"\"\"Displays multiple widgets vertically using the flexible box model.\"\"\"\n",
    "    box = Box(*pargs, **kwargs)\n",
    "    box.layout.display = 'flex'\n",
    "    box.layout.flex_flow = 'column'\n",
    "    box.layout.align_items = 'stretch'\n",
    "    return box\n",
    "\n",
    "def HBox(*pargs, **kwargs):\n",
    "    \"\"\"Displays multiple widgets horizontally using the flexible box model.\"\"\"\n",
    "    box = Box(*pargs, **kwargs)\n",
    "    box.layout.display = 'flex'\n",
    "    box.layout.align_items = 'stretch'\n",
    "    return box\n",
    "```\n",
    "\n",
    "\n",
    "### Examples"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Four buttons in a VBox. Items stretch to the maximum width, in a vertical box taking `50%` of the available space.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ipywidgets import Layout, Button, Box\n",
    "\n",
    "items_layout = Layout( width='auto')     # override the default width of the button to 'auto' to let the button grow\n",
    "\n",
    "box_layout = Layout(display='flex',\n",
    "                    flex_flow='column', \n",
    "                    align_items='stretch', \n",
    "                    border='solid',\n",
    "                    width='50%')\n",
    "\n",
    "words = ['correct', 'horse', 'battery', 'staple']\n",
    "items = [Button(description=word, layout=items_layout, button_style='danger') for word in words]\n",
    "box = Box(children=items, layout=box_layout)\n",
    "box"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Three buttons in an HBox. Items flex proportionally to their weight.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ipywidgets import Layout, Button, Box, VBox\n",
    "\n",
    "# Items flex proportionally to the weight and the left over space around the text \n",
    "items_auto = [\n",
    "    Button(description='weight=1; auto', layout=Layout(flex='1 1 auto', width='auto'), button_style='danger'),\n",
    "    Button(description='weight=3; auto', layout=Layout(flex='3 1 auto', width='auto'), button_style='danger'),\n",
    "    Button(description='weight=1; auto', layout=Layout(flex='1 1 auto', width='auto'), button_style='danger'),\n",
    " ]\n",
    "\n",
    "# Items flex proportionally to the weight \n",
    "items_0 = [\n",
    "    Button(description='weight=1; 0%', layout=Layout(flex='1 1 0%', width='auto'), button_style='danger'),\n",
    "    Button(description='weight=3; 0%', layout=Layout(flex='3 1 0%', width='auto'), button_style='danger'),\n",
    "    Button(description='weight=1; 0%', layout=Layout(flex='1 1 0%', width='auto'), button_style='danger'),\n",
    " ]\n",
    "box_layout = Layout(display='flex',\n",
    "                    flex_flow='row', \n",
    "                    align_items='stretch', \n",
    "                    width='70%')\n",
    "box_auto = Box(children=items_auto, layout=box_layout)\n",
    "box_0 = Box(children=items_0, layout=box_layout)\n",
    "VBox([box_auto, box_0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**A more advanced example: a reactive form.**\n",
    "\n",
    "The form is a `VBox` of width '50%'. Each row in the VBox is an HBox, that justifies the content with space between.."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ipywidgets import Layout, Button, Box, FloatText, Textarea, Dropdown, Label, IntSlider\n",
    "\n",
    "form_item_layout = Layout(\n",
    "    display='flex',\n",
    "    flex_flow='row',\n",
    "    justify_content='space-between'\n",
    ")\n",
    "\n",
    "form_items = [\n",
    "    Box([Label(value='Age of the captain'), IntSlider(min=40, max=60)], layout=form_item_layout),\n",
    "    Box([Label(value='Egg style'), \n",
    "         Dropdown(options=['Scrambled', 'Sunny side up', 'Over easy'])], layout=form_item_layout),\n",
    "    Box([Label(value='Ship size'), \n",
    "         FloatText()], layout=form_item_layout),\n",
    "    Box([Label(value='Information'), \n",
    "         Textarea()], layout=form_item_layout)\n",
    "]\n",
    "\n",
    "form = Box(form_items, layout=Layout(\n",
    "    display='flex',\n",
    "    flex_flow='column',\n",
    "    border='solid 2px',\n",
    "    align_items='stretch',\n",
    "    width='50%'\n",
    "))\n",
    "form"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**A more advanced example: a carousel.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ipywidgets import Layout, Button, Box, Label\n",
    "\n",
    "item_layout = Layout(height='100px', min_width='40px')\n",
    "items = [Button(layout=item_layout, description=str(i), button_style='warning') for i in range(40)]\n",
    "box_layout = Layout(overflow_x='scroll',\n",
    "                    border='3px solid black',\n",
    "                    width='500px',\n",
    "                    height='',\n",
    "                    flex_flow='row',\n",
    "                    display='flex')\n",
    "carousel = Box(children=items, layout=box_layout)\n",
    "VBox([Label('Scroll horizontally:'), carousel])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### *Compatibility note*\n",
    "\n",
    "The `overflow_x` and `overflow_y` options are deprecated in ipywidgets `7.5`. Instead, use the shorthand property `overflow='scroll hidden'`. The first part specificies overflow in `x`, the second the overflow in `y`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A widget for exploring layout options\n",
    "\n",
    "The widgets below was written by ipywidgets user [Doug Redden (@DougRzz)](https://github.com/DougRzz).\n",
    "\n",
    "Use the dropdowns and sliders in the widget to change the layout of the box containing the five colored buttons. Many of the CSS layout optoins described above are available, and the Python code to generate a `Layout` object reflecting the settings is in a `TextArea` in the widget."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from layout_preview import layout\n",
    "layout"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "widgets-tutorial",
   "language": "python",
   "name": "widgets-tutorial"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
